package com.ruiyi.controller;

import com.ruiyi.common.Result;
import com.ruiyi.common.UploadBean;
import com.ruiyi.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private UploadBean uploadBean;

    //文件上传
    @PostMapping("/uploadFile.do")
    public Result uploadFile(MultipartFile headImg, HttpServletRequest request) throws IOException {
        if(headImg.isEmpty()){
            return new Result(-1,"上传的文件不能为空");
        }
        //获取名字
        String oriName = headImg.getOriginalFilename();
        if("".equals(oriName)){
            return new Result(-1,"上传的文件的名字不能为空");
        }
        //获取后缀
        String ext = oriName.substring(oriName.lastIndexOf("."));
        //动态生成要保存的文件的名字
        //8f896bab-a295-4f69-83ed-2c0db26ecacc 就是uuid
        String uuid = UUID.randomUUID().toString();
        //确认文件最终上传的本地磁盘目录是存在的
        String saveDirPath = uploadBean.getBaseUrl();
        File file = new File(saveDirPath);
        if(!file.exists()){
            file.mkdirs();
        }
        //开始文件上传
        File finalFile = new File(saveDirPath + "/" + uuid + ext);
        headImg.transferTo(finalFile);
        //将图片地址保存到数据库的表中
        HttpSession session = request.getSession();
        Result result = accountService.modifyAccountImgUrl(uuid + ext,session);
        if(result.getCode() == 200){
            result.setData(uuid + ext);
        }
        return result;
    }

}
